<?php

namespace app\xwam\model;

/**
 * Page 模型类
 *
 * @version 1.0 2016-3-21 SoChishun(14507247@qq.com) Added.
 */
class PagesModel extends AppbaseModel {

    protected $table = 't_page';

    function savePage() {
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('category_id', 'number', '类别无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$validate->scene($isAdd ? true : 'edit')->check($data)) {
            return xsfn_message(false, $validate->getError());
        }
        //图片上传
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Page/', 'skipEmpty' => true));
        if (is_array($msg) && isset($msg['picture_url'])) {
            $data['picture_url'] = $msg['picture_url']['filepath'];
        }
        if (isset($data['create_time']) && empty($data['create_time'])) {
            unset($data['create_time']);
        }
        $categoryId=empty($data['category_id'])?false:$data['category_id'];
        if ($isAdd) {
            unset($data['id']);
            $result = $this->isUpdate(false)->save($data);
        } else {
            $id = $data['id'];
            $result = $this->isUpdate(true)->save($data);
        }
        if ($categoryId) {
            PageCategoryModel::updateForeignTitle(false, $categoryId);
        }
        return xsfn_message($result);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return xsfn_message($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return xsfn_message($result);
    }

    function deletePage($id) {
        $result = $this->where(['id' => ['in', $id]])->delete();
        return xsfn_message($result);
    }

    function saveCategory($aid, $aCategoryId) {
        $table = $this->table;
        $sqls = array();
        $upIds=array();
        $i = 0;
        foreach ($aCategoryId as $categoryId) {
            $id = $aid[$i];
            if ($categoryId) {
                $upIds[]=$categoryId;
                $sqls[] = "update $table set category_id=$categoryId where id=$id";
            }
            $i++;
        }
        if (!$sqls) {
            return xsfn_message(false, '未选择类别!');
        }
        $mAdv = new \think\Model\AdvModel();
        $mAdv->patchQuery($sqls);
        PageCategoryModel::updateForeignTitle(false, implode(',', $upIds));
        return xsfn_message(true);
    }

}
